import React from 'react'
import {withRouter} from 'react-router-dom'
import './GradePlayer.css'
import bannerSrc from '../../res/images/web/vote/活动模版／黄色2@2x.png'
import Rate from "./rate/rate";
import CustomButton from "../../shared-components/CustomButton/CustomBotton";
import {getVoteResultReq, gradePlayerReq} from "../../apis/goApis";
import LocalStorageService from "../../utils/LocalStorageService";
import {Modal, Toast} from "antd-mobile";
import GoBackLayout from "../../layouts/GoBackLayout/GoBackLayout";
import VoteGobackTab from "./vote-goback-tab/vote-goback-tab";
import {checkAndGoBack} from "../best-line-up/best-line-up";
import {onTaskDone} from "../plan-detail/plan-detail";
import TaskDoneNotice from "../plan-detail/task-done-notice/task-done-notice";
import {test} from "../../utils/constants";

const log = console.log.bind(console)

export const addLinkAndClick = (href) => {
    const link = document.createElement('a')
    link.href = href
    link.click()
}

class GradePlayer extends React.Component {

    constructor(props) {
        super(props)
        this.uid = LocalStorageService.get('userid')
        this.voteId = parseInt(this.props.match.params.id)
        this.state = {
            rate: 3,
            rated: false,
            event: '',
            player: '',
            maxScore: 5,
            ratedData: {
                score: 9.6,
                count: 500,
                detail: [
                    100,
                    100,
                    100,
                    100,
                    100,
                ],
            },
            fetchBannerFinished: false,
            taskDone: false,
            taskInfo: '',
        }
    }

    componentDidMount() {
        const params = this.searchParams()
        const webview = params.webview
        if (webview === 'true') {
            log('webview')
            this.uid = params.uid
            this.setState({
                webview: true,
            }, () => this.detail())
        } else {
            this.detail()
        }
    }

    searchParams = () => {
        const search = window.location.search
            .slice(1)
            .split('&')
            .map(keyValue => {
                return keyValue.split('=')
            })
            .reduce((acc, cur) => {
                acc[cur[0]] = cur[1]
                return acc
            }, {})
        return search
    }

    detail = () => {
        const params = {
            Uid: this.uid,
            Sid: parseInt(this.props.match.params.id),
            Flag: 1,
        }
        log(params)
        getVoteResultReq(params)
            .then(res => {
                const data = res.data.ok
                if (Array.isArray(data)) {
                    // Createt: 1614926159
                    // Endt: 1615098954
                    // Id: 10
                    // Match: "大巴黎"
                    // Score: 5
                    // Startt: 1614926154
                    // Title: "内马尔"
                    const count = data.reduce((acc, cur) => {
                        acc += cur.Count
                        return acc
                    },0)
                    const info = res.data.sr
                    log(info)
                    this.setState({
                        event: info.Match,
                        player: info.Title,
                        rate: info.Score,
                        maxScore: info.Maxscore,
                        rated: true,
                        ratedData: {
                            detail: data,
                            count,
                        },
                    }, () => this.more())
                } else {
                    this.setState({
                        event: data.Match,
                        player: data.Title,
                        maxScore: data.Score,
                    })
                }
            })
    }

    setRate = (rate) => {
        this.setState({
            rate,
        })
    }

    rate = () => {
        const rate = this.state.rate
        const params = {
            Uid: this.uid,
            Score: rate,
            Sid: this.voteId,
        }
        gradePlayerReq(params)
            .then(res => {
                const data = res.data
                if (data.ok) {
                    this.done()
                }
            })
            .then(() => {
                this.detail()
            })
    }

    done = () => {
        const uid = this.state.webview ? this.searchParams().uid : this.uid
        onTaskDone(uid, 'ltft')
            .then(data => {
                if (data.Code === 0) {
                    this.setState({
                        taskDone: true,
                        taskInfo: data.Msg,
                    })
                }
            })
    }

    more = () => {
        const webview = this.state.webview
        const end = test ? 'http://123.207.85.242:8080/ren_wu' : 'http://www.youtoball.com:8080/ren_wu'
        const btnList = [
            {
                text: <span>下次再做</span>,
                onPress: () => {},
            },
            {
                // text: webview
                //     ? <span style={{color: '#FFA500',}}>去做任务</span>
                //     : <a href={end}><span style={{color: '#FFA500',}}>去做任务</span></a>,
                text: <span style={{color: '#FFA500',}}>去做任务</span>,
                onPress: webview
                    ? () => addLinkAndClick(end)
                    : () => this.props.history.push('../../../ren_wu'),
            },
        ]
        Modal.alert(
            <span
                style={{
                    fontSize: '16px',
                    fontWeight: 500,
                    color: '#333333',
                    lineHeight: '22px',
                }}
            >'完成每日任务，可获得更多球星红包和奖励</span>,
            '合成球星越多，收益越多',
            btnList
        )
    }


    render() {

        const rate = this.state.rate
        const rated = this.state.rated
        const data = this.state.ratedData

        const rateButton = <div className='grade-player-button fade-in'>
            <CustomButton
                color={rate > 0 ? '#fff' : '#FFCC6F'}
                bg={rate > 0 ? '#FFA500' : '#E6AB40'}
                onClick={() => this.rate()}
            >
                提交
            </CustomButton>
        </div>
        const ratedTemplate = <>
            {/*<p className='grade-player-score'>*/}
            {/*    {data.score}*/}
            {/*</p>*/}
            {/*<p className='gray-text'>*/}
            {/*    {data.count}人参与评分*/}
            {/*</p>*/}
            <div className='mg-t-8px fade-in'>
                {data.detail.map((value, index) => {
                    // if (value.Score === 0) return
                    const per = ((value.Count / data.count) * 100).toFixed(2)
                    return <div key={index} >
                        <div className='flex-space-between pd-8px'>
                            <p>{value.Score + 1}颗星</p>
                            <p style={{color: '#FF8300',}}>{per}%的人选了</p>
                        </div>

                        <div
                            style={{
                                width: '100%',
                                height: '10px',
                                borderRadius: '5px',
                                background: '#FFEECF',
                                position: 'relative',
                            }}
                        >
                            <div style={{
                                width: `${per}%`,
                                height: '10px',
                                borderRadius: '5px',
                                background: '#FFA500',
                                top: '0',
                                left: '0',
                            }}/>
                        </div>
                    </div>
                })}
            </div>

        </>
        const fetchBannerFinished = this.state.fetchBannerFinished
        return <>
            {this.state.taskDone && <TaskDoneNotice taskInfo={this.state.taskInfo} onCancel={() => this.setState({taskDone: false,})}/>}
            <div
                className='grade-container'
            >

                <VoteGobackTab
                    title='打分'
                    goBack={() => checkAndGoBack(this.props.history, '../../../vote-list/player')}

                />
                <img
                    src={bannerSrc} alt='' style={{width: '100%',}}
                    onLoad={() => {
                        this.setState({
                            fetchBannerFinished: true,
                        })
                    }}
                />

                {fetchBannerFinished && <div className='grade-player-container fade-in'>
                    <div className='grade-player-event'>
                        <p>{this.state.event}</p>
                    </div>
                    <p className='grade-player-title'>
                        你给{this.state.player}的打分是
                    </p>
                    <Rate
                        value={this.state.rate}
                        count={this.state.maxScore}
                        setRate={(rate) => this.setRate(rate)}
                        disabled={this.state.rated}
                    />
                    {rated && ratedTemplate}
                </div>}
                {rated === false && fetchBannerFinished && <p className='grade-player-desc fade-in'>提交就可以看到其他球迷的评分</p>}

                {rated === false && fetchBannerFinished && rateButton}
            </div>
        </>
    }
}

export default withRouter(GradePlayer)